import React, { useState, useEffect, useRef } from 'react';
import { connect } from 'dva';
import { Card, Form, Input, Button, message, Modal, Tooltip, Divider } from 'antd';
import request from '@/utils/request';
import SlickTable from '@/components/SlickTable';
import useSlickTableTemp from '@/hooks/useSlickTableTemp';
import styles from '../styles.less';
import AttrSpecAdd from './AttrSpecAdd';

// 判断空对象
const isEmptyObject = obj => {
  if (Object.keys(obj).length === 0) {
    return true;
  }
  return false;
};

const namespace = 'busiObjManage';

function AttrSpecInfo(props) {
  const addFormEl = useRef();
  const [params, setParams] = useState({
    busiObjId: props.selectBusiObj.busiObjId || 999999999999999,
  }); // 列表查询参数
  const [AttrSpecAddTitle, setAttrSpecAddTitle] = useState('新增属性规格');

  useEffect(() => {
    setParams({
      ...params,
      busiObjId: props.selectBusiObj.busiObjId || 999999999999999,
      gb_reset: true,
    });
    saveSelectAttrSpec({});
  }, [props.selectBusiObj]);

  // 初始化表格数据
  const { tableProps } = useSlickTableTemp({ pageSize: 5 }, 'pmc/pms/attrSpec/queryPage', params);

  const queryForm = () => {
    setParams({
      ...params,
    });
  };

  const handleSearch = value => {
    setParams({
      ...params,
      attrNbrOrName: value,
    });
  };

  // 通过dva传递
  const saveAttrSpecAddVisibleFlag = params => {
    const { dispatch } = props;
    dispatch({
      type: `${namespace}/saveAttrSpecAddVisibleFlag`,
      payload: params,
    });
  };

  const saveAttrSpecAddType = params => {
    const { dispatch } = props;
    dispatch({
      type: `${namespace}/saveAttrSpecAddType`,
      payload: params,
    });
  };

  const saveSelectAttrSpec = params => {
    const { dispatch } = props;
    dispatch({
      type: `${namespace}/saveSelectAttrSpec`,
      payload: params,
    });
  };

  const handleAdd = () => {
    if (isEmptyObject(props.selectBusiObj)) {
      Modal.warning({ content: '请先选中一个业务对象' });
      return;
    }
    setAttrSpecAddTitle('新增属性规格');
    saveAttrSpecAddVisibleFlag(true);
    saveAttrSpecAddType('add');
  };

  const handleModify = record => {
    saveSelectAttrSpec(record);
    setAttrSpecAddTitle('修改属性规格');
    saveAttrSpecAddVisibleFlag(true);
    saveAttrSpecAddType('modify');
  };

  const handleDelete = record => {
    Modal.confirm({
      content: '确定删除选中属性规格？',
      okText: '确定',
      cancelText: '取消',
      onOk() {
        request('pmc/pms/attrSpec/delete', {
          method: 'GET',
          data: { attrId: record.attrId },
        }).then(res => {
          if (res && res.success === true) {
            message.success('删除成功');
            saveSelectAttrSpec({});
            queryForm();
          } else if (res && res.errMessage) {
            message.error(res.errMessage);
          } else {
            message.error('删除失败');
          }
        });
      },
    });
  };

  const handleOk = () => {
    addFormEl.current.handleAdd().then(res => {
      if (res === true) {
        saveAttrSpecAddVisibleFlag(false);
        queryForm();
      }
    });
  };

  const handleCancel = () => {
    saveAttrSpecAddVisibleFlag(false);
  };

  const columns = [
    {
      title: '属性规格名称',
      dataIndex: 'attrName',
      render: (text, record) => {
        return <Tooltip>{record.attrName}</Tooltip>;
      },
    },
    {
      title: '属性规格编码',
      dataIndex: 'attrNbr',
    },
    {
      title: '操作',
      render: (text, record) => {
        return (
          <span>
            {props.selectBusiObj.busiTypeId !== 1000 ? (
              <div>
                <a
                  onClick={() => {
                    handleModify(record);
                  }}
                >
                  编辑
                </a>
                <Divider type="vertical" />
                <a
                  onClick={() => {
                    handleDelete(record);
                  }}
                >
                  删除
                </a>
              </div>
            ) : null}
          </span>
        );
      },
    },
  ];

  return (
    <div>
      <Card
        className="cute"
        title="属性规格"
        extra={
          <div className={styles.extra}>
            <div>
              <Input.Search
                className={styles.Button}
                style={{ width: '200px' }}
                placeholder="属性名称、编码搜索"
                onSearch={handleSearch}
              />
            </div>
            <div>
              {props.selectBusiObj.busiTypeId !== 1000 ? (
                <Button type="primary" className="margin-right" onClick={() => handleAdd()}>
                  新增属性规格
                </Button>
              ) : null}
            </div>
          </div>
        }
      >
        <SlickTable
          rowKey={record => record.attrId}
          columns={columns}
          {...tableProps}
          rowClassName={record => {
            return record.attrId === props.selectAttrSpec.attrId ? styles.clickRowStyle : '';
          }}
          onRow={record => {
            return {
              onClick: () => {
                saveSelectAttrSpec(record);
              },
            };
          }}
        />
      </Card>

      {/* 新增属性规格 */}
      <Modal
        title={AttrSpecAddTitle}
        visible={props.attrSpecAddVisibleFlag}
        onOk={handleOk}
        onCancel={handleCancel}
        width="70%"
        destroyOnClose
      >
        <AttrSpecAdd cRef={addFormEl} />
      </Modal>
    </div>
  );
}
export default connect(({ busiObjManage }) => ({
  selectBusiObj: busiObjManage.selectBusiObj,
  selectAttrSpec: busiObjManage.selectAttrSpec,
  attrSpecAddVisibleFlag: busiObjManage.attrSpecAddVisibleFlag,
  attrSpecAddType: busiObjManage.attrSpecAddType,
}))(Form.create({})(AttrSpecInfo));
